<template>
  <div class="creator-apply">
    <div class="page-header">
      <h1 class="page-title">申请成为创作者</h1>
      <p class="page-desc">请填写以下表单，我们将在3-5个工作日内审核您的申请</p>
    </div>

    <div class="apply-container" v-loading="loading">
      <div v-if="applicationStatus && applicationStatus.status !== 'none'" class="status-container">
        <div class="status-card" :class="getStatusClass(applicationStatus.status)">
          <div class="status-icon">
            <i :class="getStatusIcon(applicationStatus.status)"></i>
          </div>
          <div class="status-content">
            <h2 class="status-title">{{ getStatusTitle(applicationStatus.status) }}</h2>
            <p class="status-message">{{ applicationStatus.message }}</p>
            <p class="status-time">申请时间: {{ applicationStatus.applyTime }}</p>
            <div class="status-actions" v-if="applicationStatus.status === 'rejected'">
              <el-button type="primary" @click="resetForm">重新申请</el-button>
            </div>
          </div>
        </div>
      </div>

      <el-form
        v-else
        ref="applyForm"
        :model="applyForm"
        :rules="rules"
        label-width="120px"
        class="apply-form"
      >
        <h3 class="form-section-title">基本信息</h3>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="applyForm.realName" placeholder="请输入您的真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="applyForm.idNumber" placeholder="请输入您的身份证号"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="applyForm.phone" placeholder="请输入您的联系电话"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="applyForm.email" placeholder="请输入您的电子邮箱"></el-input>
        </el-form-item>

        <h3 class="form-section-title">专业信息</h3>
        <el-form-item label="专业领域" prop="field">
          <el-select v-model="applyForm.field" placeholder="请选择您的专业领域">
            <el-option
              v-for="item in fieldOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教育背景" prop="education">
          <el-select v-model="applyForm.education" placeholder="请选择您的最高学历">
            <el-option label="专科" value="college"></el-option>
            <el-option label="本科" value="bachelor"></el-option>
            <el-option label="硕士" value="master"></el-option>
            <el-option label="博士" value="doctor"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验" prop="experience">
          <el-input-number v-model="applyForm.experience" :min="0" :max="50" placeholder="请输入您的工作年限"></el-input-number>
          <span class="unit-label">年</span>
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction">
          <el-input
            type="textarea"
            v-model="applyForm.introduction"
            :rows="4"
            placeholder="请简要介绍您的专业背景和教学经验"
          ></el-input>
        </el-form-item>

        <h3 class="form-section-title">创作计划</h3>
        <el-form-item label="创作方向" prop="direction">
          <el-checkbox-group v-model="applyForm.direction">
            <el-checkbox label="course">课程</el-checkbox>
            <el-checkbox label="ppt">PPT课件</el-checkbox>
            <el-checkbox label="video">视频课件</el-checkbox>
            <el-checkbox label="material">学习资料</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="创作计划" prop="plan">
          <el-input
            type="textarea"
            v-model="applyForm.plan"
            :rows="4"
            placeholder="请描述您的创作计划，包括内容类型、主题、目标受众等"
          ></el-input>
        </el-form-item>
        <el-form-item label="作品样例" prop="sampleUrl">
          <el-input v-model="applyForm.sampleUrl" placeholder="请提供您的作品链接（如有）"></el-input>
        </el-form-item>

        <h3 class="form-section-title">资质证明</h3>
        <el-form-item label="证书上传" prop="certificates">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="certificateList"
            :on-change="handleCertificateChange"
            :on-remove="handleCertificateRemove"
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">支持JPG、PNG格式，不超过5MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="协议" prop="agreement">
          <el-checkbox v-model="applyForm.agreement">我已阅读并同意<a href="javascript:;" @click="showAgreement">《创作者协议》</a></el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitApplication">提交申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 协议对话框 -->
    <el-dialog
      title="创作者协议"
      :visible.sync="dialogVisible"
      width="60%"
    >
      <div class="agreement-content">
        <h3>创作者协议</h3>
        <p>本协议由您与教育平台（以下简称"平台"）共同缔结，本协议具有合同效力。</p>
        <h4>1. 定义</h4>
        <p>1.1 创作者：指通过平台审核，在平台上发布教育内容的个人或组织。</p>
        <p>1.2 内容：指创作者在平台上发布的课程、课件、视频、文档等教育资源。</p>
        
        <h4>2. 权利与义务</h4>
        <p>2.1 创作者保证其发布的内容不侵犯任何第三方的合法权益。</p>
        <p>2.2 创作者授权平台对其发布的内容进行分发、推广和商业化运营。</p>
        <p>2.3 平台负责为创作者提供内容发布、管理和收益分配等服务。</p>
        
        <h4>3. 收益分配</h4>
        <p>3.1 平台将根据内容的受欢迎程度、质量评价等因素，按照约定比例与创作者分享收益。</p>
        <p>3.2 具体分成比例将在创作者后台公示，平台保留调整分成比例的权利。</p>
        
        <h4>4. 内容审核</h4>
        <p>4.1 创作者发布的所有内容需符合平台的内容规范和相关法律法规。</p>
        <p>4.2 平台有权对违规内容进行下架或删除处理。</p>
        
        <h4>5. 协议期限</h4>
        <p>5.1 本协议自创作者申请通过之日起生效，至创作者账号注销之日终止。</p>
        <p>5.2 平台保留根据实际情况修改本协议的权利。</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="agreeToTerms">同意</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'CreatorApply',
  data() {
    const validateIdNumber = (rule, value, callback) => {
      if (value && !/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/.test(value)) {
        callback(new Error('请输入正确的身份证号码'))
      } else {
        callback()
      }
    }
    
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    
    return {
      loading: false,
      applicationStatus: null,
      applyForm: {
        realName: '',
        idNumber: '',
        phone: '',
        email: '',
        field: '',
        education: '',
        experience: 0,
        introduction: '',
        direction: [],
        plan: '',
        sampleUrl: '',
        certificates: [],
        agreement: false
      },
      certificateList: [],
      dialogVisible: false,
      fieldOptions: [
        { value: 'math', label: '数学' },
        { value: 'english', label: '英语' },
        { value: 'physics', label: '物理' },
        { value: 'chemistry', label: '化学' },
        { value: 'biology', label: '生物' },
        { value: 'history', label: '历史' },
        { value: 'geography', label: '地理' },
        { value: 'politics', label: '政治' },
        { value: 'computer', label: '计算机' },
        { value: 'art', label: '艺术' },
        { value: 'music', label: '音乐' },
        { value: 'other', label: '其他' }
      ],
      rules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdNumber, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        field: [
          { required: true, message: '请选择专业领域', trigger: 'change' }
        ],
        education: [
          { required: true, message: '请选择教育背景', trigger: 'change' }
        ],
        experience: [
          { required: true, message: '请输入工作经验', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入个人简介', trigger: 'blur' },
          { min: 50, max: 500, message: '长度在50到500个字符之间', trigger: 'blur' }
        ],
        direction: [
          { type: 'array', required: true, message: '请至少选择一个创作方向', trigger: 'change' }
        ],
        plan: [
          { required: true, message: '请输入创作计划', trigger: 'blur' },
          { min: 100, max: 1000, message: '长度在100到1000个字符之间', trigger: 'blur' }
        ],
        certificates: [
          { required: true, message: '请上传资质证明', trigger: 'change' }
        ],
        agreement: [
          { type: 'boolean', required: true, message: '请阅读并同意协议', trigger: 'change', transform: value => value === true }
        ]
      }
    }
  },
  created() {
    this.checkApplicationStatus()
  },
  methods: {
    async checkApplicationStatus() {
      this.loading = true
      try {
        const response = await api.creator.getCreatorApplicationStatus()
        this.applicationStatus = response.data
      } catch (error) {
        console.error('获取申请状态失败:', error)
        this.$message.error('获取申请状态失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    handleCertificateChange(file, fileList) {
      this.certificateList = fileList
      this.applyForm.certificates = fileList.map(item => item.raw)
    },
    handleCertificateRemove(file, fileList) {
      this.certificateList = fileList
      this.applyForm.certificates = fileList.map(item => item.raw)
    },
    showAgreement() {
      this.dialogVisible = true
    },
    agreeToTerms() {
      this.applyForm.agreement = true
      this.dialogVisible = false
    },
    submitApplication() {
      this.$refs.applyForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            const formData = new FormData()
            Object.keys(this.applyForm).forEach(key => {
              if (key === 'certificates') {
                this.applyForm.certificates.forEach(file => {
                  formData.append('certificates', file)
                })
              } else if (key === 'direction') {
                formData.append('direction', this.applyForm.direction.join(','))
              } else {
                formData.append(key, this.applyForm[key])
              }
            })
            
            await api.creator.applyForCreator(formData)
            this.$message.success('申请提交成功，请等待审核')
            this.checkApplicationStatus()
          } catch (error) {
            console.error('提交申请失败:', error)
            this.$message.error('提交申请失败，请稍后重试')
          } finally {
            this.loading = false
          }
        } else {
          this.$message.warning('请完善表单信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.applyForm.resetFields()
      this.certificateList = []
      this.applyForm.certificates = []
    },
    getStatusClass(status) {
      const classMap = {
        pending: 'status-pending',
        approved: 'status-approved',
        rejected: 'status-rejected'
      }
      return classMap[status] || ''
    },
    getStatusIcon(status) {
      const iconMap = {
        pending: 'el-icon-loading',
        approved: 'el-icon-check',
        rejected: 'el-icon-close'
      }
      return iconMap[status] || ''
    },
    getStatusTitle(status) {
      const titleMap = {
        pending: '申请审核中',
        approved: '申请已通过',
        rejected: '申请被拒绝'
      }
      return titleMap[status] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.creator-apply {
  padding: 20px;

  .page-header {
    text-align: center;
    margin-bottom: 30px;

    .page-title {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #303133;
    }

    .page-desc {
      font-size: 16px;
      color: #606266;
    }
  }

  .apply-container {
    max-width: 800px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 8px;
    padding: 30px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .form-section-title {
    font-size: 18px;
    font-weight: bold;
    margin: 20px 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    color: #303133;
  }

  .unit-label {
    margin-left: 10px;
    color: #606266;
  }

  .status-container {
    .status-card {
      display: flex;
      align-items: center;
      padding: 30px;
      border-radius: 8px;

      &.status-pending {
        background-color: #e6f7ff;
        border: 1px solid #91d5ff;
      }

      &.status-approved {
        background-color: #f6ffed;
        border: 1px solid #b7eb8f;
      }

      &.status-rejected {
        background-color: #fff2f0;
        border: 1px solid #ffccc7;
      }

      .status-icon {
        font-size: 48px;
        margin-right: 20px;

        .el-icon-loading {
          color: #1890ff;
        }

        .el-icon-check {
          color: #52c41a;
        }

        .el-icon-close {
          color: #f5222d;
        }
      }

      .status-content {
        flex: 1;

        .status-title {
          font-size: 20px;
          font-weight: bold;
          margin-bottom: 10px;
        }

        .status-message {
          font-size: 14px;
          margin-bottom: 10px;
          color: #606266;
        }

        .status-time {
          font-size: 12px;
          color: #909399;
          margin-bottom: 15px;
        }
      }
    }
  }

  .agreement-content {
    max-height: 400px;
    overflow-y: auto;
    padding: 0 10px;

    h3 {
      font-size: 18px;
      margin-bottom: 15px;
      text-align: center;
    }

    h4 {
      font-size: 16px;
      margin: 15px 0 10px;
    }

    p {
      margin-bottom: 10px;
      line-height: 1.6;
      color: #606266;
    }
  }
}

@media (max-width: 768px) {
  .creator-apply {
    .apply-container {
      padding: 20px 15px;
    }
  }
}
</style> 